import { getCommTreeByXid, s_getcommontableinfo, s_getcommontableinfoBycondition, s_getFileInfo, s_getTableInfo, s_operateInfo, s_updateInfo } from "@/services/basis";
import { getSelection } from "@/services/selections";
import { StepForwardFilled } from "@ant-design/icons";
import { ActionType, ProCard, ProColumns, ProColumnType, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components";
import { useRequest } from "@umijs/max";
import { Button, Card, Col, GetProp, Image, List, message, Modal, Row, Space, Steps, Tabs, TabsProps, Tag, Tree, TreeNodeProps, Upload, UploadProps } from "antd"
import { DataNode } from "antd/es/tree";
import moment, { RFC_2822 } from "moment";
import { Divider } from "rc-menu";
import { useEffect, useRef, useState } from "react";

    //定义样品第一步主表单组件
 function SampleForm(props:{etype:any,fdata:any,mform_ref:any,mform2_ref:any}){
   const [formProgressId,setFormProgressId]=useState(0);
   const [fileInfo,setFileInfo]=useState("");
   const [filename,setFilename]=useState("");
   const [additions,setAdditions]=useState<any[]>(props.fdata==null||JSON.parse(props.fdata.addition)==null?[]:JSON.parse(props.fdata.addition));
   const [currentData,setCurrentData]=useState(()=>{
         //  alert('组件中的新值：'+JSON.stringify(props.fdata));
          return props.fdata;});

    const step1_tab1=<><ProForm formRef={props.mform_ref} submitter={false}
                      initialValues={
                        props.etype==0?{
                        ...props.fdata,
                        operate_time:moment().format('YYYY-MM-DD'),}
                      :{
                         operate_time:moment().format('YYYY-MM-DD'),
                         status:1,
                         sample_progress_id:formProgressId,
                          
                       }}
                        style={{height:520}}
                    >
                  <Row gutter={8}>
                     <Col span={6}>
                     {/* {JSON.stringify(formProgressId)} */}
                     <ProFormSelect name='sample_progress_id' label='样品流程' 
                            request={async ()=>{
                               var x:any=await getSelection({source:'base_sample_progress',x_id:1});
                               var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                               x2.push({value:0,label:'请选择'});
                               return x2;
                              }}
                        /> 
                        <ProFormSelect name='org_id' label='申请部门' 
                            request={async ()=>{
                              var x:any=await getSelection({source:'base_organization',x_id:1});
                              var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                              return x2;
                             }}
                        /> 
                        <ProFormSelect name='operater_id' label='申请人' 
                            request={async ()=>{
                              var x:any=await getSelection({source:'base_person',x_id:1});
                              var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                              return x2;
                             }}
                         /> 
                        <ProFormSelect name='x_id' label='组织ID' hidden={true} /> 
                        <ProFormText name='id' label='单据ID' hidden={true}  /> 
                     </Col>
                     <Col span={6}>
                         <ProFormText name='code' label='样品编号' /> 
                         <ProFormSelect name='sample_category_id' label='样品分类'
                            request={async ()=>{
                              var x:any=await getSelection({source:'base_sample_category',x_id:1});
                              var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                              return x2;
                             }}
                         /> 
                         <ProFormText name='order_code' label='订单号' /> 
                    </Col>
                     <Col span={6}>
                         <ProFormText name='name' label='样品名称' />
                         <ProFormSelect name='to_xid' label='制样供应商'  
                             request={async ()=>{
                              var x:any=await getSelection({source:'v_vendor',x_id:1});
                              var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                              return x2;
                             }}
                         /> 
                         <ProFormSelect name='vendor_vcid' label='专用供应商' 
                             request={async ()=>{
                              var x:any=await getSelection({source:'vcdocument',x_id:1});
                              var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                              return x2;
                             }}
                         /> 
                         
                         <ProFormSelect name='source_xid' label='来源组织' hidden={true} /> 
                          <ProFormSelect name='business_id' label='业务员' 
                              request={async ()=>{
                                 var x:any=await getSelection({source:'base_person',x_id:1});
                                 var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                                 return x2;
                                }}
                         /> 
                     </Col>
                     <Col span={6}>
                     <ProFormDatePicker name='enddate' label='需求时间' /> 
                     <ProFormSelect name='custom_vcid' label='专用客户' 
                        request={async ()=>{
                           var x:any=await getSelection({source:'vcdocument',x_id:1});
                           var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                           return x2;
                          }}
                     /> 
                          <ProFormDatePicker name='operate_time' label='操作时间' /> 
                          
                          <ProFormRadio.Group name='status' label='状态' hidden={props.fdata==null?true:false}
                             options={[{value:0,label:'进行中'},{value:1,label:'已完结'},{value:2,label:'冻结'},{value:3,label:'删除'}]}
                          />
                     </Col>
                  </Row>
                   
                  <ProFormText name='memo' label='备注' /> 
                  <ProFormTextArea name='description' label='样品具体要求' /> 
                 </ProForm></>;
    
    //文件列表,载入时为全部
   //  var addit:any[]=JSON.parse(props.fdata.addition);
   //  setAdditions(addit);

    //附件列表项.etype:1增加，2删除
    async function operateItem(type:number,item2:string){
       var temp=additions;
       if(type==1)
           temp.push(item2);
        else
           temp=temp.filter((item:string)=>item!=item2)
         //   alert(JSON.stringify(item2));  
      //  alert(JSON.stringify(temp));
       const fdata={id:props.fdata.id,additions:temp};
      //  source,x_id,operater_id,etype,fdata
       const x=await s_updateInfo({source:'sample',x_id:1,operater_id:1,etype:3,fdata}); 
       if(x.success){
           message.success('删除附件成功');
           setAdditions(temp);
       }else
           message.error('删除附件失败，请联系管理员');
    }
   
    //限制上传文件类型
    type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
    const beforeUpload = (file: FileType) => {
       // alert(file.name.substring(file.name.indexOf('.')+1));
        const  sufix=file.name.substring(file.name.indexOf('.')+1);
        const isPicture = sufix === 'jpg' || sufix === 'jpeg'|| sufix === 'bmp'|| sufix === 'png'|| sufix === 'pdf';
        if (!isPicture) {
             message.error('错误！只可以导入图片（jpg/jpeg/bmp/png）或PDF文件!');
        }
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isLt2M) {
             message.error('错误！要导入的文件必须小于10MB!');
        }
        return  isPicture&&isLt2M;
        };
        
      const step1_tab2=<><ProForm submitter={false} style={{height:576}} formRef={props.mform2_ref}
                              initialValues={{addition:additions}}
                            >
                               <Upload
                                     name='upfile'
                                     action='/basis_api/upload/file/htoms2'
                                     beforeUpload={beforeUpload}
                                     data={{x_id:1,operater_id:1,source:'sample',
                                            tdata:JSON.stringify({id:props.fdata==null?0:props.fdata.id,step:0,
                                             code:props.fdata==null?'':props.fdata.code})}}
                                     onChange={(info)=>{
                                          if(info.file.status=='done'){
                                               message.success('文件上传成功！')
                                             //   alert(info.file.name);
                                               var t=[...additions];
                                               t.push(info.file.name);
                                               alert(JSON.stringify(t));
                                               setAdditions(t);
                                            };
                                          if(info.file.status=='error')
                                               message.error('文件上传失败'+info.file.error);
                                            }}
                                  >
                              <Button style={{width:200}}>上传文档附件(限图片或PDF)</Button>
                             </Upload>
                               <ProFormText name='addition' label='附件列表' hidden={true}/>
                               <Row gutter={8}>
                                   <Col span={6}>
                                   <Card title='附件列表'  style={{height:500}}>
                                          <List
                                             dataSource={additions}
                                             renderItem={(item,index)=>{
                                                return <List.Item
                                                       onClick={async ()=>{
                                                      //   调用源文件并显示
                                                      //文件默认统一存放在c:/additions下,需拼接文件路径（不含前缀）
                                                      //样品路径：c:/additions+组织ID+sample/样品编号/步骤序号/文件名
                                                       const filename0='c:/additions/'.concat('1','/sample/',props.fdata.code,'/0/',item);
                                                      //  const x=await s_getFileInfo({filename:filename0}); 
                                                          setFileInfo('/basis_api/file/get?filename='+filename0);
                                                         //  alert(filename0);
                                                      //  alert('/basis_api/file/get?filename='+filename0)
                                                          setFilename(item);
                                                       }}
                                                     >
                                                       
                                                             <span style={{width:'75%'}}>{item}</span> 
                                                          
                                                         
                                                             <Button  
                                                                  onClick={(e)=>{
                                                                       e.preventDefault();
                                                                       operateItem(2,item);
                                                                }}>删除</Button>
                                                 
                                                       </List.Item>
                                                     }}
                                          />
                                      </Card>
                                   </Col>
                                    <Col span={18}>
                                      <Card title='文档预览' style={{height:500}}>
                                       {filename.toLowerCase().indexOf(".pdf")<=0?
                                        <Image src={fileInfo} style={{ width: '100%', height: 400 }}/>
                                        :<iframe
                                             title="PDF预览"
                                              style={{ width: '100%', height: 400 }}
                                              src={fileInfo}
                                          />
                                       } 
                                      </Card>
                                   </Col>
                               </Row>
                              
                        </ProForm></>;

    const step1_item:TabsProps["items"]=[
      {
         label: '样品明细',
         children: <>{step1_tab1}</>,
         key: "tab1",
      },{
         key:"tab2",
         label:'样品申请附件',
         children:<>{step1_tab2}</>,
         disabled:props.fdata==null?true:false,
         // disabled:currentData==null?true:false,
      }
    ];

    return (<>
            {/* 组件内值：{JSON.stringify(currentData)} */}
            <Tabs items={step1_item} type="card"/>
            </>
           )
   }
  
   // function Temp(props:{stepno:any,pdata:any}){
   //    const [xx,setXX]=useState(0);
   //    function x(){
   //       setXX(9);
   //       alert(props.pdata.code);
   //    }
   //    return <>
   //       {JSON.stringify( props.stepno)}
   //       {JSON.stringify( props.pdata)}
   //       <ProFormText name='ss' label='测试组件' />
   //       <Button onClick={()=>x()}>dddd</Button>
   //       </>
   // }
   //定义1-6步组件，主要包含上传附件和审批意见----注意：详情页为0。
   //参数：表单所属的步骤号，本步骤的审批意见和附件清单（opinion和stepX_addition[]）,表单引用（用于取值保存）
   function Stepx(props:{stepno:number,pindata:any,form_ref:any}){
      const [fileInfo,setFileInfo]=useState("");
      const [filename,setFilename]=useState("");
      // const [additions,setAdditions]=useState([]);
     const [itemList,setItemList]=useState(()=>{
         if(props.pindata==null)
            return [];
         else
          switch(props.stepno){
            case 1: return props.pindata.step1_addition==null||JSON.parse(props.pindata.step1_addition)==null?[]:JSON.parse(props.pindata.step1_addition);
            case 2: return props.pindata.step2_addition==null||JSON.parse(props.pindata.step2_addition)==null?[]:JSON.parse(props.pindata.step2_addition);
            case 3: return props.pindata.step3_addition==null||JSON.parse(props.pindata.step3_addition)==null?[]:JSON.parse(props.pindata.step3_addition);
            case 4: return props.pindata.step4_addition==null||JSON.parse(props.pindata.step4_addition)==null?[]:JSON.parse(props.pindata.step4_addition);
            case 5: return props.pindata.step5_addition==null||JSON.parse(props.pindata.step5_addition)==null?[]:JSON.parse(props.pindata.step5_addition);
            case 6: return props.pindata.step6_addition==null||JSON.parse(props.pindata.step6_addition)==null?[]:JSON.parse(props.pindata.step6_addition);
            default:return []; 
        }
       });

      const [formInfo,setFormInfo]=useState<{id:any,step_state:any,step_verify_id:any,step_opinion:any,code:any}>(():any=>{
         if(props.pindata==null)
               return {id:0,step_state:0,step_verify_id:0,step_opinion:'',code:''};
         else
            switch(props.stepno){
            case 1: return {step_state:props.pindata.step1_state,step_verify_id:props.pindata.step1_verify_id,
                               step_opinion:props.pindata.step1_opinion,id:props.pindata.id,code:props.pindata.code};
            case 2: return {step_state:props.pindata.step2_state,step_verify_id:props.pindata.step2_verify_id,
                               step_opinion:props.pindata.step2_opinion,id:props.pindata.id,code:props.pindata.code};
            case 3: return {step_state:props.pindata.step3_state,step_verify_id:props.pindata.step3_verify_id,
                               step_opinion:props.pindata.step3_opinion,id:props.pindata.id,code:props.pindata.code};
            case 4: return {step_state:props.pindata.step4_state,step_verify_id:props.pindata.step4_verify_id,
                               step_opinion:props.pindata.step4_opinion,id:props.pindata.id,code:props.pindata.code};
            case 5: return {step_state:props.pindata.step5_state,step_verify_id:props.pindata.step5_verify_id,
                               step_opinion:props.pindata.step5_opinion,id:props.pindata.id,code:props.pindata.code};
            case 6: return {step_state:props.pindata.step6_state,step_verify_id:props.pindata.step6_verify_id,
                               step_opinion:props.pindata.step6_opinion,id:props.pindata.id,code:props.pindata.code};
        }
        
      });
      
      async function getAddition(){
         const x=await s_getcommontableinfoBycondition({x_id:1,source:'sample_detail',
                         tdata:{type:1,id:props.pindata.id,stepno:props.stepno}});
         const y=x.data[0][0].step_addition;
         //   alert(JSON.stringify(x.data[0][0]));
         //返回附件清单
          setItemList(y==null?[]:JSON.parse(y));
          //返回审批意见等
         //  alert("更新后的数据："+JSON.stringify(x.data[0][0]));
         const d=x.data[0][0];
          setFormInfo({id:d.id,step_opinion:d.step_opinion,step_verify_id:d.step_verify_id,step_state:d.step_state,code:d.code});
         //  props.form_ref.currnent?.setFieldsValue({...x.data[0][0]});
           props.form_ref.current?.setFieldsValue({id:d.id,step_opinion:d.step_opinion,step_verify_id:d.step_verify_id,step_state:d.step_state});
      }

      useEffect(()=>{
         // alert(props.stepno);
         // alert(JSON.stringify(props.pindata));
         // alert(props.stepno);
         getAddition();
      },[props.stepno]);

      //先按传入的步骤，计算对应步骤的数据
      const pdata=props.pindata;
      
      // alert(JSON.stringify(pdata));
      
      // if(props.stepno==1)
         // setFormInfo("6666");
      // setFormInfo({step_addition:props.pindata.addition});
      // alert(props.stepno);
      //  alert("fromInfo:"+JSON.stringify(formInfo));
     //附件列表项.etype:1增加，2删除
    async function operateItem(type:number,item2:string){
      var temp=[...itemList];
      if(type==1)
          temp.push(item2);
       else
          temp=temp.filter((item:string)=>item!=item2)
         //  alert(JSON.stringify(item2));  
      //  alert(JSON.stringify(temp));

      // const fdata={id:props.pindata.id,stepno:props.stepno,additions:temp};
      const fdata={id:formInfo.id,stepno:props.stepno,additions:temp};
     //  source,x_id,operater_id,etype,fdata
      const x=await s_updateInfo({source:'sample',x_id:1,operater_id:1,etype:4,fdata}); 
      if(x.success){
          message.success('删除附件成功');
          setItemList(temp);
      }else
          message.error('删除附件失败，请联系管理员');
   }
  
   //限制上传文件类型
   type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
   const beforeUpload = (file: FileType) => {
      // alert(file.name.substring(file.name.indexOf('.')+1));
       const  sufix=file.name.substring(file.name.indexOf('.')+1);
       const isPicture = sufix === 'jpg' || sufix === 'jpeg'|| sufix === 'bmp'|| sufix === 'png'|| sufix === 'pdf';
       if (!isPicture) {
            message.error('错误！只可以导入图片（jpg/jpeg/bmp/png）或PDF文件!');
       }
       const isLt2M = file.size / 1024 / 1024 < 10;
       if (!isLt2M) {
            message.error('错误！要导入的文件必须小于10MB!');
       }
       return  isPicture&&isLt2M;
       };
       
       return (<>
          <ProForm submitter={false} style={{height:576}} formRef={props.form_ref}
                                initialValues={{
                                     ...formInfo,
                                    step_state:formInfo.step_state!=5&&formInfo.step_state!=6?0:formInfo.step_state,
                                    //   step_state:6,
                                }}
                            >
                              {JSON.stringify(formInfo)}
                              <Row gutter={8}>
                                 <Col span={4}>
                                 <Space hidden={true}>
                                   <Upload
                                     name='upfile'
                                     action='/basis_api/upload/file/htoms2'
                                     beforeUpload={beforeUpload}
                                     data={props.pindata==null?{}:{x_id:1,operater_id:1,source:'sample',
                                           tdata:JSON.stringify({id:props.pindata.id,step:props.stepno,
                                             code:props.pindata.code})}}
                                     onChange={(info)=>{
                                          if(info.file.status=='done'){
                                               message.success('文件上传成功！')
                                             //   alert(info.file.name);
                                               var t=[...itemList];
                                               t.push(info.file.name);
                                               setItemList(t);
                                            };
                                          if(info.file.status=='error')
                                               message.error('文件上传失败'+info.file.error);
                                            }}
                                        >
                                            <Button style={{width:200}}>上传附件(限图片或PDF)</Button>
                                   </Upload>
                                   </Space>
                                 </Col>
                                 
                                 <Col span={10}>
                                    <ProFormText name='step_opinion' label='审核意见'                               
                                    />
                                 </Col>
                                 <Col span={5}>
                                   <ProFormRadio.Group name="step_state" label='审核状态'
                                       options={[{value:0,label:'未审核',disabled:true},{value:5,label:'评审通过'},{value:6,label:'评审不通过',style:{color:'red'}}]}
                                     /> 
                                 </Col>
                                 <Col span={5}>
                                    <ProFormSelect name='step_verify_id' label='审核人'
                                          request={async ()=>{
                                             var x:any=await getSelection({source:'base_person',x_id:1});
                                             var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                                             return x2;
                                            }}
                                    />
                                 </Col>
                              </Row>
                            
                               {/* {JSON.stringify(props.pindata)} */}
                               {props.stepno}--
                               {itemList}--{JSON.stringify(formInfo)}
                               <ProFormText name='step_addition' label='附件列表' hidden={true}/>
                               <Row gutter={8}>
                                   <Col span={6}>
                                   <Card title='附件列表'  style={{height:500}}>
                                          <List
                                             dataSource={itemList}
                                             renderItem={(item:string,index)=>{
                                                return <List.Item
                                                       onClick={async ()=>{
                                                      //   调用源文件并显示
                                                      //文件默认统一存放在c:/additions下,需拼接文件路径（不含前缀）
                                                      //样品路径：c:/additions+组织ID+sample/样品编号/步骤序号/文件名
                                                       const filename0='c:/additions/'.concat('1','/sample/',props.pindata.code,'/',props.stepno.toString(),'/',item);
                                                      //  const x=await s_getFileInfo({filename:filename0}); 
                                                          setFileInfo('/basis_api/file/get?filename='+filename0);
                                                         //  alert(filename0);
                                                      //  alert('/basis_api/file/get?filename='+filename0)
                                                          setFilename(item);
                                                       }}
                                                     >
                                                      <span style={{width:'75%'}}>{item}</span> 
                                                             <Button  hidden={true}
                                                                  onClick={(e)=>{
                                                                       e.preventDefault();
                                                                       operateItem(2,item);
                                                                }}>删除</Button>
                                                 
                                                       </List.Item>
                                                     }}
                                          />
                                      </Card>
                                   </Col>
                                    <Col span={18}>
                                      <Card title='文档预览' style={{height:500}}>
                                       {filename.toLowerCase().indexOf(".pdf")<=0?
                                        <Image src={fileInfo} style={{ width: '100%', height: 400 }}/>
                                        :<iframe
                                             title="PDF预览"
                                              style={{ width: '100%', height: 400 }}
                                              src={fileInfo}
                                          />
                                       } 
                                      </Card>
                                   </Col>
                               </Row>
                         </ProForm>
       </>);
   }

const App:React.FC=()=>{
   const [treeData,setTreeData]=useState();
   const [selectNode,setSelectNode]=useState<DataNode>();
   const [selectCategoryID,setSelectCategoryID]=useState<any[]>([]);
   const [selectedRecord,setSelectedRecord]=useState<DataType[]>([]);
    
   const [selectedRowId,setSelectedRowId]=useState([]);
   const [queryCondition,setQueryCondition]=useState({type:2});
   const [sampleProgressSelectOptions,setSampleProgressSelectOptions]=useState([]);

   const [sampleItems,setSampleItems]=useState<{title:string,description:string,content:any}[]>([{title:'请选择样品流程',description:'请选择样品流程',content:<></>}]);
   const [formProgressId,setFormProgressId]=useState(0);

   const [open,setOpen]=useState(false);
   const [etype,setEtype]=useState(1);
   const [current,setCurrent]=useState(0);
   const [stepData,setStepData]=useState<any>();
   
   const mtable_ref=useRef<ActionType>();
   const mform_ref=useRef<ProFormInstance>();
   const mform2_ref=useRef<ProFormInstance>();
   const stable_ref=useRef<ActionType>();

   const form_progress=useRef<ProFormInstance>();
   
   const stepForm_ref=useRef<ProFormInstance>();
    
   
 
   useRequest(()=>getCommTreeByXid({x_id:1,source_table:'base_sample_category'}),{  
      onSuccess:(data)=>setTreeData(data),
    });
   
   useRequest(()=>getSelection({source:'base_sample_progress',x_id:1}),{
      onSuccess:(data)=>{
        var x=data.map((item:any)=>({value:item.id,label:item.name}));
        x.push({value:0,label:'请选择'});
        setSampleProgressSelectOptions(x);
      }
   });
 
     //切换Step时，获取附件及审批信息
     async function onChange(value:number){
          //样品表单详情页，不需要取审批过程数据
          if(value!=0){
         // 先重新获取数据stepData，再更新current.
        const x=await s_getcommontableinfoBycondition({x_id:1,source:'sample_detail',
                         tdata:{type:1,id:stepData.id,stepno:value}});
         // const y=x.data[0][0].step_addition;
         //   alert('切换后的审批内容：'+JSON.stringify(x.data[0][0]));
         //   alert('节点值：'+JSON.stringify(stepData));
           setStepData(x.data[0][0]);
         }else{
            //重新获取样品表单详表信息----有可能更改了表单信息
            const x=await s_getcommontableinfo({x_id:1,source:'v_sample',id:selectedRecord[0].id,cate_id:selectCategoryID});
            // alert('重新获取更新后的表单值：'+JSON.stringify(x.data[0]));
            setSelectedRecord(x.data[0]);
         }
          
         //切换审批过程当前序号
         setCurrent(value);
       }             

     const onModalClose=()=>{
         // setFormProgressId(0);
         setSampleItems([{title:'请选择样品流程',description:'请选择样品流程',content:<></>}]);
         setSelectedRecord([]);
         mtable_ref.current?.reloadAndRest?.();
         setStepData({});
         // setStepData({id:0,step_opinion:'',step_verify_id:0,step_addition:null,step_state:0});
         // setStepData({});
         // setEtype(1);
         setCurrent(0);
         setOpen(false);
     };
   
    //点击左侧树
    function selectTreeNode(node:DataNode){
      setSelectNode(node);
      // alert(JSON.stringify(node));
      arr=[];//先置为空，再取数据
      arr.push(node.key);
      getNodeKeys(node);
      setSelectCategoryID(arr.filter((item)=>item!=null));
      
      mtable_ref.current?.reloadAndRest?.();
    }

   //  新增
   function add(){
      if(selectCategoryID.length==0)
         message.warning('请先选择类别');
      else{
         setEtype(1);
         // setOpen(true);
         // setFormProgressId(0);
         // mtable_ref.current?.reset?.();
         setSelectedRecord([]);
         //   setSampleForm(0);
          setOpen(true);
          
      }
   }
    //  审核
    function verify(){
      if(selectedRecord.length==0)
         message.warning('请先要审核的行');
      else{
         setEtype(0);
         setOpen(true);
         setSampleForm(selectedRecord[0].sample_progress_id);
       }
   }
    
   //保存样品表单---注意：只是第一步，非后续的审核环节。应返回最新记录值
   async function saveInfo(){
        const tdata2=mform_ref.current?.getFieldsValue();
        const tdata={...tdata2,enddate:moment(moment(tdata2.enddate).toDate()).format('YYYY-MM-DD'),
                        id:etype==0?selectedRecord[0].id:0};
       alert("etype:"+etype);
        const x=await s_updateInfo({x_id:1,operater_id:1,source:'sample',etype,fdata:tdata});
      if(x.success){
          message.success('保存成功');
         //  setOpen(false);
         //  setEtype(1);
          alert(JSON.stringify(x.data[0]));
          setSelectedRecord(x.data[0]);
          
          mtable_ref.current?.reloadAndRest?.();
          
          
          // 如果是新增表单保存，需返回对应的样品过程设置信息,用于后续节点取对应的附件信息
           if(etype==1){
                 const y=await s_getcommontableinfoBycondition({x_id:1,source:'v_sample_progress',
                           tdata:{progress_id:x.data[0].sample_progress_id,
                                   id:x.data[0].id}});
                 setStepData(y.data[1][0]);
                 setEtype(0);
             }
       }else
          message.error('保存失败，请联系管理员');
   }

   //样品过程审核----参数：审核1，撤销审核0
   async function verifyStep(type:number){
      if(type==1){  //审核--同时保存审核意见、状态等
        const tdata2=stepForm_ref.current?.getFieldsValue();
       const tdata={...tdata2,stepno:current,id:stepData?.id,mid:selectedRecord[0].id};
        alert(JSON.stringify(tdata));
        const x=await s_updateInfo({x_id:1,operater_id:1,source:'sample',etype:5,fdata:tdata});
      if(x.success){
          message.success('审核成功');
         mtable_ref.current?.reloadAndRest?.();
        }else
          message.error('审核失败，请联系管理员');
   }else{
       //撤销审核，置状态为state-7。撤销审核后，供应方可查看（sate:2/7）
       //state状态：1未下达，2已下达，3回复同意，4回复拒绝，5审核同意，6审核不同意，7撤销审核
       //status:0未审核，1已审核/完结，2冻结，3删除，4审核不同意
       //上述规则，适用于全系统
         const x2=await s_updateInfo({x_id:1,source:'sample',operater_id:1,etype:6,fdata:{stepno:current,id:stepData?.id}});
         if(x2.success){
            message.success('撤销节点审核成功');
            mtable_ref.current?.reloadAndRest?.();
         }else
            message.error('撤销失败，请联系管理员。');
       }
   }

   //  操作
   async function operateInfo(n:number){
      // source,x_id,operater_id,otype,id
      if(selectedRecord.length==0)
         message.warning('请选择要操作的行');
      else{
       const x=await s_operateInfo({x_id:1,source:'sample',operater_id:1,otype:n,id:selectedRecord[0].id});
       if(x.success){
         message.success('操作成功');
         mtable_ref.current?.reloadAndRest?.();
       }else
         message.error('操作错误，请联系管理员。');
      }
   }
 
   //下达至供应商   --1下达，0撤回
   async function sendToVendor(type:number){
      const to_xid=mform_ref.current?.getFieldValue('to_xid');
      alert(to_xid);
      if(to_xid==null)
         message.warning('请选择制样供应商，再下达');
      else{
          const x=await s_updateInfo({source:'sample',x_id:1,operater_id:1,etype:7,fdata:{id:selectedRecord[0].id,to_xid,type}});
          if(x.success){
                message.success('下达成功');
                mtable_ref.current?.reloadAndRest?.();
         }else{
                message.error('下达失败，请联系管理员');
         };
      };
   }

    //生成样品流程表单
    async function setSampleForm(progress_id:number){
      // alert('progress_id:'+progress_id);
      var items:any[]=[];
        setFormProgressId(progress_id);
        
      //新增时仅显示首表单
      if(progress_id==0){

          items.push({title:"新增打样申请",description:"请选择打样流程",
                 content:<><SampleForm etype={etype} mform_ref={mform_ref} 
                         fdata={selectedRecord[0]} mform2_ref={mform2_ref} /></>
             });
          setSampleItems(items);
      }
      //当选择样品流程后，重新生成流程和表单
      if(progress_id!=0){
        items=[];
        items.push({title:"发起申请",description:"样品单明细",
         content:<><SampleForm etype={etype} mform_ref={mform_ref} 
           fdata={selectedRecord[0]}  mform2_ref={mform2_ref}/></>
       });
       
       const x=await s_getcommontableinfoBycondition({x_id:1,source:'v_sample_progress',
                    tdata:{progress_id,id:selectedRecord.length==0?0:selectedRecord[0].id}});
        // 返回第一个表为主表过程data[0],第二个表为样品过程明细表data[1]
       //   此处需添加样品单据号code,作为存储路径
       //   alert(JSON.stringify({...x.data[1][0],code:x.data[0][0].code}));
        setStepData(x.data[1][0]);
      //   alert(JSON.stringify(x.data[1][0]));
       //   alert("dddd"+JSON.stringify(x.data[0]));
        x.data[0].map((item:any)=>{
                 if(item.step1!=null)
                    items.push({title:item.step1,description:item.step1_description,
                               content:<></>,disabled:selectedRecord.length==0?true:false,
                     }) 
                 else {
                        setSampleItems(items);
                        return;
                     };

                 if(item.step2!=null)
                    items.push({title:item.step2,description:item.step2_description,
                               content:<></>,disabled:selectedRecord.length==0?true:false,
                     }) 
                 else {
                        setSampleItems(items);
                        return;
                     };
                  if(item.step3!=null)
                       items.push({title:item.step3,description:item.step3_description,
                                  content:<></>,disabled:selectedRecord.length==0?true:false,
                        }) 
                    else {
                       setSampleItems(items);
                       return;
                        };   
                    if(item.step4!=null)
                          items.push({title:item.step4,description:item.step4_description,
                                     content:<></>,disabled:selectedRecord.length==0?true:false,
                           }) 
                       else {
                          setSampleItems(items);
                          return;
                       }; 
                    if(item.step5!=null)
                             items.push({title:item.step5,description:item.step5_description,
                                        content:<></>,disabled:selectedRecord.length==0?true:false,
                              }) 
                          else {
                             setSampleItems(items);
                             return;
                          };
                     if(item.step6!=null)
                                items.push({title:item.step6,description:item.step6_description,
                                           content:<></>,disabled:selectedRecord.length==0?true:false,
                                 }) 
                             else {
                                setSampleItems(items);
                                return;
                             };
                  
             });

             //取出样品的多步骤流程数据
          }
           //   alert(etype);
           //   setOpen(true);
           
           //   mform_ref.current?.setFieldsValue({...selectedRecord[0]});
           }

  //--生成本级和下级的分类ID数组---先取本节点及下级节点值，再共同选
      var arr:any[]=[];
       //定义一个递归函数，获取选中节点下的所有key
      //  function getNodeKeys(node:{key:any,title:any,children:any[]}){
         function getNodeKeys(node:any){
            if(node.children.length>0)
                  node.children.map((item:any)=>{
                     arr.push(item.key);
                     if(item.children.length>0){
                          arr.push(getNodeKeys(item));
                     }
                 });
          }
      
          interface DataType{
            //  id,code,name,org_id,operater_id,sample_category_id,sample_category_name,operate_time,description,
            //  order_code,business_id,sample_progress_id,memo,vendor_vcid,status,enddate,custom_vcid,org_name,
            //  operater_name,business_name,sample_progress_name,custom_name,vendor_name
            id:number,code:string,name:string,org_id:number,operater_id:number,sample_category_id:number,
            sample_category_name:string,operate_time:string,description:string,
             order_code:string,business_id:number,sample_progress_id:number,memo:string,vendor_vcid:number,status:number,
             enddate:string,custom_vcid:number,org_name:string,addition:string,source_xid:number,to_xid:number,
             operater_name:string,business_name:string,sample_progress_name:string,custom_name:string,vendor_name:string,
             source_name:string,to_name:string,state:number,
          }

          
          const columns:ProColumns<DataType>[]=[
            {dataIndex:'id',hidden:true},{dataIndex:'org_id',hidden:true},{dataIndex:'operater_id',hidden:true},{dataIndex:'addition',hidden:true},
            {dataIndex:'sample_category_id',hidden:true},{dataIndex:'business_id',hidden:true},{dataIndex:'sample_progress_id',hidden:true},
            {dataIndex:'custom_vcid',hidden:true},{dataIndex:'vendor_vcid',hidden:true},{dataIndex:'sample_progress_name',hidden:true},
            {dataIndex:'org_name',title:'申请部门'},{dataIndex:'sample_category_name',title:'样品分类'},{dataIndex:'code',title:'样品编号'},
            {dataIndex:'name',title:'样品名'},{dataIndex:'description',title:'具体需求',width:'10%'},
            {dataIndex:'to_xid',hidden:true},{dataIndex:'source_xid',hidden:true},{dataIndex:'to_name',title:'制样供应商'},
            {dataIndex:'enddate',title:'要求完成日期',
               render:(text:any)=>moment(moment(text).toDate()).format('YYYY-MM-DD'),
            },
            {dataIndex:'order_code',title:'订单号'},{dataIndex:'custom_name',title:'专用客户'},{dataIndex:'vendor_name',title:'专用供应商'},
            {dataIndex:'business_name',title:'业务员'},{dataIndex:'memo',title:'备注'},
            {dataIndex:'operater_name',title:'申请人'},
            {dataIndex:'operate_time',title:'申请日期',
               render:(text:any)=>moment(moment(text).toDate()).format('YYYY-MM-DD'),
            },
            {dataIndex:'state',title:'进度',
               render:(text)=>{
               switch (text) {
                  case 1: return '未下达';
                  case 2: return '已下达';
                  case 3: return '供方已接收';
                  case 4: return '供方已拒绝';
                  case 5: return '已评审确认';
                  case 6: return '已评审拒绝';
                  case 7: return '撤销评审'; 
                  case 8: return '供方撤销提交';
               }}
            },
            {dataIndex:'status',title:'状态',fixed:'right',width:80,
               render:(text)=>{
                  switch(text){
                     case 0: return <Tag >进行中</Tag>;break;
                     case 1: return <Tag >已完结</Tag>;break;
                     case 2: return <Tag color="blue" >冻结</Tag>;break;
                     case 3: return <Tag  color="red">删除</Tag>;break;
                     case 4: return <Tag >已审未通过</Tag>;break;
                  }
               }
            }, 
          ];

     return (
        <Row gutter={8}>
         <Col span={6}  >
           <ProCard title='样品分类' style={{height:700}}>
               {/* {JSON.stringify(selectCategoryID)} */}
               <Tree treeData={treeData} defaultExpandAll blockNode onClick={(e,node)=>selectTreeNode(node)} />
           </ProCard>  
         </Col>
         <Col span={18}  >
           <ProCard title='样品单' style={{height:700}} 
            extra={<Space>
                    <Button onClick={()=>add()}>新增</Button>
                    <Button onClick={()=>verify()}>审核</Button>
                    <Button onClick={()=>operateInfo(2)}>冻结</Button>
                    <Button onClick={()=>operateInfo(3)}>删除</Button>
                    <Button onClick={()=>operateInfo(1)}>恢复</Button>
            </Space>}
           >
            {/* {JSON.stringify(selectedRecord)} */}
               <ProTable<DataType> 
                   actionRef={mtable_ref}
                   columns={columns}
                   rowKey='id'
                   rowSelection={{
                     type:'radio',
                     // onSelect:(selectedRows:any,selectedRowKeys)=>setSelectedRecord(selectedRows),
                     onSelect:(record,selected,selectedRows)=>{
                     // onSelect:(selectedRowKeys:any, selectedRows, info)=>{
                         setSelectedRecord(selectedRows);
                        // setSampleForm(selectedRowKeys[0]);
                        // alert(JSON.stringify(selectedRows));
                        // setEtype(0);
                        // setFormProgressId(selectedRows[0].sample_progress_id);
                     },
                     fixed:'left',
                   }}
                   pagination={{
                     pageSize:6,
                     showQuickJumper:true,
                   }}
                   request={async ()=>{
                     // x_id,cate_id,id,source
                     const x=await s_getcommontableinfo({x_id:1,source:'v_sample',id:0,cate_id:selectCategoryID});
                     return{
                        data:x.data[0],
                        success:true,
                     }
                   }}
                   scroll={{x:'200%'}}
                   search={false}
                />

           </ProCard>
         </Col>
          
        <Modal open={open} destroyOnClose closable okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
                   onCancel={()=>onModalClose()} onClose={()=>onModalClose()} width={'80%'}  
                >
                   <Steps items={sampleItems} current={current} type="navigation" onChange={onChange} />
                     <ProCard title='样品过程管理' 
                         extra={<Space>
                              <Button hidden={current!==0?true:false} onClick={()=>saveInfo()}>保存</Button>
                              <Button hidden={current!=0?true:false} onClick={()=>sendToVendor(1)}>下达至供应商</Button>
                              <Button hidden={current!=0?true:false} onClick={()=>sendToVendor(0)}>撤回下达</Button>
                              <Button onClick={()=>verifyStep(1)} hidden={current==0||stepData.step_state!=3?true:false}>节点审核</Button>
                              <Button onClick={()=>verifyStep(0)} hidden={current==0||(stepData.step_state!=5&&stepData.step_state!=6)?true:false}>撤销节点审核</Button>
                        </Space>}
                     >
                        <ProForm formRef={form_progress} submitter={false}
                              initialValues={{sample_progress_id:0}}
                              >
                                  <ProFormSelect name='sample_progress_id' label='样品流程' style={{width:200}}
                                           request={async ()=>sampleProgressSelectOptions}
                                           onChange={(value:any)=>{
                                             //   setFormProgressId(value);
                                               setSampleForm(value);
                                             //   alert(formProgressId);
                                               mform_ref.current?.setFieldValue("sample_progress_id",value);
                                             //   alert(JSON.stringify(mform_ref.current?.getFieldValue("sample_progress_id")));
                                          }}
                                   /> 
                        </ProForm>
                         
                        {/* <>{ sampleItems[current].content} </> */}
                        {/* {JSON.stringify(stepData)} */}
                        {/* {JSON.stringify(selectedRecord[0])} */}
                        {current==0?<SampleForm etype={etype} mform_ref={mform_ref} mform2_ref={mform2_ref}
                                       fdata={selectedRecord[0]}  />:<Stepx stepno={current} pindata={stepData} form_ref={stepForm_ref} /> }
                           
                                       
                           
                     </ProCard>
                </Modal>
        </Row>
     );
}
 

export default App;